#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/14 10:55
# @Author  : harry
import threading
import time

import requests
from pytz import unicode
from wechatpy import WeChatClient

from dvadmin_wechat.models import OfficialAccountManagement, FanTags, FanGroups, FanManagement

SYNC_SIGNAL = False
SYNC_SIGNAL1 = [False]
from dvadmin.utils.json_response import ErrorResponse, DetailResponse, SuccessResponse

SUBSCRIBE_SCENE = {"ADD_SCENE_SEARCH": "公众号搜索", "ADD_SCENE_ACCOUNT_MIGRATION": "公众号迁移",
                   "ADD_SCENE_PROFILE_CARD": "名片分享", "ADD_SCENE_QR_CODE": "扫描二维码", "ADD_SCENE_PROFILE_LINK": "图文页内名称点击",
                   'ADD_SCENE_PROFILE_ITEM': "图文页右上角菜单", 'ADD_SCENE_PAID': "支付后关注",
                   "ADD_SCENE_WECHAT_ADVERTISEMENT": "微信广告",
                   'ADD_SCENE_REPRINT': "他人转载", 'ADD_SCENE_LIVESTREAM': '视频号直播', 'ADD_SCENE_CHANNELS': "视频号",
                   "ADD_SCENE_OTHERS": "其他"
                   }


def sync_fan_management(official_account_management_id):
    if official_account_management_id:
        o_a_m_sum = OfficialAccountManagement.objects.filter(id=official_account_management_id, status=1)
    else:
        o_a_m_sum = OfficialAccountManagement.objects.filter(status=1)
    for i in o_a_m_sum:
        # 同步标签
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                i.appid, i.app_secret))
        if "access_token" in res.text:
            access_token = res.json().get('access_token')
        else:
            return ErrorResponse("请求达到上线")
        if "access_token" in res.text:
            tags = requests.get(
                url='https://api.weixin.qq.com/cgi-bin/tags/get?access_token={}'.format(access_token))
            if "tags" in tags.text:
                for b in tags.json().get("tags"):
                    if "\\u" in b.get("name"):
                        name = b.get("name").encode('utf-8').decode("unicode_escape")
                    else:
                        name = b.get("name")
                    f_t = FanTags.objects.filter(official_account_management=i, tagsid=b.get("id")).first()
                    if f_t:
                        f_t.name = name
                        f_t.save()
                    else:
                        FanTags.objects.create(name=name, tagsid=b.get("id"),
                                               official_account_management=i)
        # 同步组
        client = WeChatClient(i.appid, i.app_secret)
        for b in client.group.get():
            f_g = FanGroups.objects.filter(official_account_management=i, groupid=b.get("id")).first()
            if f_g:
                f_g.name = b.get("name")
                f_g.save()
            else:
                FanGroups.objects.create(official_account_management=i, name=b.get("name"), groupid=b.get("id"), )

        if i.appid and i.app_secret:
            client = WeChatClient(i.appid, i.app_secret)
            openid_list = [openid for openid in client.user.iter_followers()]
            sum_openid_list = len(openid_list)
            # if sum_openid_list // 100 > 0:
            for b in range((sum_openid_list // 100) + 1):
                users = client.user.get_batch(openid_list[b * 100:(b + 1) * 100])
                fanmanagement_post_list = []
                fanmanagement_update_list = []
                f_m_tagid_list = []
                for c in users:
                    timeArray = time.localtime(c.get('subscribe_time'))
                    subscribe_time = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
                    groupid = c.get("groupid")  # 组id
                    f_g = FanGroups.objects.filter(groupid=groupid, official_account_management=i).first()
                    f_m = FanManagement.objects.filter(official_account_management=i,
                                                       open_id=c.get("openid")).first()
                    if not f_m:
                        if c.get("tagid_list"):
                            tagid_ids = FanTags.objects.filter(
                                official_account_management=i,
                                tagsid__in=c.get("tagid_list")).values_list('id', flat=True)

                            f_m_tagid_list.append({c.get("openid"): tagid_ids})
                        if c.get('subscribe_scene') in SUBSCRIBE_SCENE.keys():
                            subscribe_scene = SUBSCRIBE_SCENE[c.get('subscribe_scene')]
                        else:
                            subscribe_scene = c.get('subscribe_scene')
                        fanmanagement_post_list.append(
                            FanManagement(official_account_management=i, name=c.get("nickname"),
                                          head_portrait=c.get('headimgurl'),
                                          language=c.get('language'), subscribe=c.get('subscribe'),
                                          subscribe_scene=subscribe_scene, fan_groups=f_g,
                                          remark=c.get("remark"), union_id=c.get("unionid"),
                                          open_id=c.get("openid"),
                                          subscribe_time=subscribe_time)
                        )
                    else:
                        if c.get("tagid_list"):
                            tagid_ids = FanTags.objects.filter(
                                official_account_management=i,
                                tagsid__in=c.get("tagid_list")).values_list('id', flat=True)

                            f_m_tagid_list.append({c.get("openid"): tagid_ids})
                        f_m = FanManagement.objects.filter(
                            official_account_management=i, open_id=c.get("openid")).first()
                        f_m.name = c.get("nickname")
                        f_m.head_portrait = c.get('headimgurl')
                        f_m.subscribe = c.get('subscribe')
                        f_m.union_id = c.get("unionid")
                        f_m.fan_groups = f_g
                        f_m.language = c.get('language')
                        f_m.remark = c.get("remark")
                        fanmanagement_update_list.append(f_m)

                FanManagement.objects.bulk_update(fanmanagement_update_list,
                                                  ['name', 'head_portrait', 'subscribe', 'union_id', 'language',
                                                   'remark', 'fan_groups'])
                FanManagement.objects.bulk_create(fanmanagement_post_list)
                for k_v in f_m_tagid_list:
                    f_m = FanManagement.objects.filter(open_id=list(k_v.keys())[0]).first()
                    f_m.fan_tags.clear()
                    f_m.fan_tags.set(list(k_v.values())[0])
                    # list(f_m.keys())[0],list(f_m.values())[0]
            # 同步拉黑的粉丝
            black_list = requests.post(
                url='https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={}'.format(
                    access_token), json={})
            if black_list.json().get("total") <= 1000:
                if black_list.json().get("total") > 0:
                    # print(black_list.json(), ">>>>>>>>black_list.json()")
                    for b in black_list.json().get("data").get("openid"):
                        f_m = FanManagement.objects.filter(official_account_management=i,
                                                           open_id=b).first()
                        f_m.is_black = 0
                        f_m.save()
            else:
                for b in black_list.json().get("data").get("openid"):
                    f_m = FanManagement.objects.filter(official_account_management=i,
                                                       open_id=b).first()
                    f_m.is_black = 0
                    f_m.save()
                v_range = black_list.json().get("total") // 1000
                if v_range > 1:
                    next_openid = black_list.json().get("data").get("next_openid")
                    for c in range(v_range):
                        new_black_list = requests.post(
                            url='https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={}'.format(
                                access_token),
                            json={"begin_openid": next_openid})
                        for b in new_black_list.json().get("data").get("openid"):
                            f_m = FanManagement.objects.filter(official_account_management=i,
                                                               open_id=b).first()
                            f_m.is_black = 0
                            f_m.save()
                        next_openid = new_black_list.json().get("data").get("next_openid")
                else:
                    new_black_list = requests.post(
                        url='https://api.weixin.qq.com/cgi-bin/tags/members/getblacklist?access_token={}'.format(
                            access_token),
                        json={"begin_openid": black_list.json().get("data").get("next_openid")})
                    for b in new_black_list.json().get("data").get("openid"):
                        f_m = FanManagement.objects.filter(official_account_management=i,
                                                           open_id=b).first()
                        f_m.is_black = 0
                        f_m.save()
    return DetailResponse(data=None, msg="操作成功")


def sync_tag_list(is_black=None, official_account_management_id=None, openid_list=None, tagid_list=None, is_one=None):
    o_a_m = OfficialAccountManagement.objects.filter(id=official_account_management_id,
                                                     status=1).first()
    if o_a_m:
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                o_a_m.appid, o_a_m.app_secret))
        if "access_token" in res.text:
            access_token = res.json().get('access_token')
        else:
            return ErrorResponse("请求达到上线")
    else:
        return ErrorResponse(msg='请输入正确的公众号')

    if is_one:
        for tagid in tagid_list:
            f_t = FanTags.objects.filter(official_account_management=o_a_m, tagsid=tagid).first()
            if not f_t:
                return ErrorResponse("请输入该公众号下正确的标签")
            if str(tagid) == '2':
                return ErrorResponse("不可设置标签为星标组")
            # openid_list = str(request.data.get("openid_list")).split(',')[:-1]
            if not openid_list:
                return ErrorResponse(msg='请至少传递一个用户')
            openid_dict = {"openid_list": openid_list, "tagid": tagid}
            black_list = requests.post(
                url='https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={}'.format(
                    access_token), json=openid_dict)
            if "ok" not in black_list.json().get("errmsg"):
                return ErrorResponse(msg='打标签失败')
        for c in openid_list:
            f_m = FanManagement.objects.filter(
                official_account_management_id=official_account_management_id,
                open_id=c).first()
            if f_m:
                tagid_ids = FanTags.objects.filter(
                    official_account_management_id=official_account_management_id,
                    tagsid__in=tagid_list).values_list('id', flat=True)
                f_m.fan_tags.clear()
                f_m.fan_tags.set(tagid_ids)
        return SuccessResponse(msg='操作完成')
    else:
        is_black = 0 if str(is_black) == '0' else 1
        for tagid in tagid_list:
            f_t = FanTags.objects.filter(official_account_management=o_a_m, tagsid=tagid).first()
            if not f_t:
                return ErrorResponse("请输入该公众号下正确的标签")
            if str(tagid) == '2':
                return ErrorResponse("不可设置标签为星标组")
            # openid_list = str(request.data.get("openid_list")).split(',')[:-1]
            if not openid_list:
                return ErrorResponse(msg='请至少传递一个用户')
            openid_list_sum = len(openid_list)
            for i in range((openid_list_sum // 20) + 1):
                openid_dict = {"openid_list": openid_list[i * 20:(i + 1) * 20], "tagid": tagid}
                if is_black == 0:
                    black_list = requests.post(
                        url='https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={}'.format(
                            access_token), json=openid_dict)
                    if "ok" not in black_list.json().get("errmsg"):
                        return ErrorResponse(msg='打标签失败')
                    for c in openid_list:
                        f_m = FanManagement.objects.filter(
                            official_account_management_id=official_account_management_id,
                            open_id=c).first()
                        if f_m:
                            tagid_ids = FanTags.objects.filter(
                                official_account_management_id=official_account_management_id,
                                tagsid__in=tagid_list).values_list('id', flat=True)
                            f_m.fan_tags.remove(tagid_ids)
                    return DetailResponse(data=None, msg=black_list.json().get("errmsg"))
                else:
                    black_list = requests.post(
                        url='https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={}'.format(
                            access_token), json=openid_dict)
                    if "ok" not in black_list.json().get("errmsg"):
                        return ErrorResponse(msg='打标签失败')
                    for c in openid_list:
                        f_m = FanManagement.objects.filter(
                            official_account_management_id=official_account_management_id,
                            open_id=c).first()
                        if f_m:
                            tagid_ids = FanTags.objects.filter(
                                official_account_management_id=official_account_management_id,
                                tagsid__in=tagid_list).values_list('id', flat=True)
                            f_m.fan_tags.set(tagid_ids | f_m.fan_tags.all().values_list('id', flat=True))
                    return DetailResponse(data=None, msg=black_list.json().get("errmsg"))
    return SuccessResponse(msg='操作完成')


def sync_black_list(is_black, openid_list, official_account_management_id):
    o_a_m = OfficialAccountManagement.objects.filter(id=official_account_management_id,
                                                     status=1).first()
    # openid_list = str(request.data.get("openid_list")).split(',')[:-1]
    if not openid_list:
        return ErrorResponse("openid必传")
    openid_list_sum = len(openid_list)
    if o_a_m:
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                o_a_m.appid, o_a_m.app_secret))
        if "access_token" in res.text:
            access_token = res.json().get('access_token')
        else:
            return ErrorResponse("请求达到上线")
        for i in range(openid_list_sum // 20 + 1):
            openid_dict = {"openid_list": openid_list[i * 20:(i + 1) * 20]}
            if is_black == 1:
                black_list = requests.post(
                    url='https://api.weixin.qq.com/cgi-bin/tags/members/batchunblacklist?access_token={}'.format(
                        access_token), json=openid_dict)
                for c in openid_list:
                    f_m = FanManagement.objects.filter(official_account_management=o_a_m,
                                                       open_id=c).first()
                    f_m.is_black = 1
                    f_m.save()
                return DetailResponse(data=None, msg=black_list.json().get("errmsg"))
            else:
                black_list = requests.post(
                    url='https://api.weixin.qq.com/cgi-bin/tags/members/batchblacklist?access_token={}'.format(
                        access_token), json=openid_dict)
                for c in openid_list:
                    f_m = FanManagement.objects.filter(official_account_management=o_a_m,
                                                       open_id=c).first()
                    f_m.is_black = 0
                    f_m.save()
                return DetailResponse(data=None, msg=black_list.json().get("errmsg"))
    return DetailResponse(data=None, msg="操作成功")


def sync_remark(remark, official_account_management_id, openid_list):
    o_a_m = OfficialAccountManagement.objects.filter(id=official_account_management_id,
                                                     status=1).first()
    if o_a_m:
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                o_a_m.appid, o_a_m.app_secret))
        if "access_token" in res.text:
            access_token = res.json().get('access_token')
        else:
            return ErrorResponse("请求达到上线")
        for c in openid_list:
            remark_data = {"remark": remark, "openid": c}
            black_list = requests.post(
                url='https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token={}'.format(
                    access_token), json=remark_data)
            if "0" == str(black_list.json().get("errcode")):
                f_m = FanManagement.objects.filter(official_account_management=o_a_m, open_id=c).first()
                if f_m:
                    f_m.remark = remark
                    f_m.save()
            else:
                return ErrorResponse(msg=black_list.json().get("errmsg"))


def sync_tags(official_account_management):
    tagsid_list = []
    old_tagsid_list = []
    if official_account_management:
        o_a_m_sum = OfficialAccountManagement.objects.filter(id=official_account_management, status=1)
    else:
        o_a_m_sum = OfficialAccountManagement.objects.filter(status=1)
    for i in o_a_m_sum:
        for b in FanTags.objects.filter(official_account_management=i):
            old_tagsid_list.append({"id": b.id, "tagsid": int(b.tagsid)})
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                i.appid, i.app_secret))
        if "access_token" in res.text:
            tags = requests.get(url='https://api.weixin.qq.com/cgi-bin/tags/get?access_token={}'.format(
                res.json().get('access_token')))
            if "tags" in tags.text:
                for b in tags.json().get("tags"):
                    if "\\u" in b.get("name"):
                        name = b.get("name").encode('utf-8').decode("unicode_escape")
                    else:
                        name = b.get("name")
                    f_t = FanTags.objects.filter(official_account_management=i, tagsid=b.get("id")).first()
                    if f_t:
                        f_t.name = name
                        f_t.save()
                        tagsid_list.append({"id": f_t.id, "tagsid": b.get("id")})
                    else:
                        f_t = FanTags.objects.create(name=name, tagsid=b.get("id"),
                                                     official_account_management=i)
                        tagsid_list.append({"id": f_t.id, "tagsid": b.get("id")})
    id_list = []
    for item in old_tagsid_list:
        if item not in tagsid_list:
            id_list.append(item.get("id"))
    if id_list:
        FanTags.objects.filter(id__in=id_list).delete()
    return DetailResponse(data=None, msg="同步成功")


def sync_groups(official_account_management):
    if official_account_management:
        o_a_m_sum = OfficialAccountManagement.objects.filter(id=official_account_management, status=1)
    else:
        o_a_m_sum = OfficialAccountManagement.objects.filter(status=1)
    for i in o_a_m_sum:
        client = WeChatClient(i.appid, i.app_secret)
        for b in client.group.get():
            f_g = FanGroups.objects.filter(official_account_management=i, groupid=b.get("id")).first()
            if f_g:
                f_g.name = b.get("name")
                f_g.save()
            else:
                FanGroups.objects.create(official_account_management=i, name=b.get("name"), groupid=b.get("id"), )
    return DetailResponse(data=None, msg="同步成功")
